//app.js

/**
 * 页面缓存
 */
import __Pages from 'source/js/pages'

/**
 *全局配置 
 */
const GlobalConfig = {
// API_Url: "https://www.m12315.com/mgjser/"
  // API_Url: "http://192.168.0.111:789/"
  API_Url: "https://www.tryapi.cn/nbapi/"
}

/**
 * 扩展方法
 */
const __extend = function (pSource, sSource) {
  for (var item in sSource) {
    if (sSource[item]) {
      pSource[item] = sSource[item]
    }
  }
}

/**
 *Ajax 请求 
 */
const __ajax = function (options, __showloading) {
  var _options = {
    url: "",
    dataType: "json",
    method: "GET",
    success: function (r) { },
    fail: function (e) { },
  }

  __extend(_options, options);

  wx.request(_options);
}



/**
 *Ajax 请求 扩展
 */
const __set_ajax = function (__url, __data, __success, __fail, __type, __showloading = true) {
  if (__showloading) {
    wx.showNavigationBarLoading();
    wx.showLoading({
      title: '加载中...',
      mask:true
    })
  }
  if (!__fail) {
  
    __fail = function (e) {
      wx.showModal({
        title: '提示',
        content: e,
        showCancel: false
      })
    }
  }
  __ajax({
    url: GlobalConfig.API_Url + __url,
    dataType: "json",
    method: __type,
    data: __data,
    header: {
      "Access-Token": wx.getStorageSync('__token'),
      "Access-Sign": wx.getStorageSync('__sign'),
      "Access-TimeSpan": (new Date()).valueOf(),
      'content-type': 'application/json'
    },
    success: function (r) {
      wx.hideNavigationBarLoading();
      var __rCode = r.statusCode;
      if (__rCode == 200) {
        if (r.data.success) {
          if (__success) { __success(r.data.result); }
        } else {
          if (__fail) { __fail(r.data.message); }
        }
      } else {
        if (__rCode == 204) {
          var _current = getCurrentPages();
          var _temp = "../";
          for (var i = 1; i < _current.length; i++) {
            _temp += "../";
          }
          wx.redirectTo({
            url: _temp + 'my/logon/logon',
          })
        } else if (__rCode == 500) {
          if (__fail) { __fail(r.data.ExceptionMessage); }
        }
      }
      wx.hideLoading();
    },
    fail: function (e) {
      wx.hideLoading();
      wx.hideNavigationBarLoading();
      if (__fail) { __fail(e); }
    }
  }, __showloading);
}

/**
 * 获取微信OPENID
 */
wx["$$getOpenid"] = function (callback) {
  wx.login({
    success: function (res) {
      wx.request({
        url: "https://api.weixin.qq.com/sns/jscode2session?appid=wxa645333b1a6df7b5&secret=39439a095cd24c84a8b3d08bb876f0d0&js_code=" + res.code + "&grant_type=authorization_code",
        success: function (r) {
          if (callback) { callback(r.data.openid); }
        }
      })
    }
  })
}

wx["$$getWXUserInfo"]= function(callback){
  // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.userInfo" 这个 scope
  wx.getSetting({
    success(res) {
      if (!res['scope.userInfo']) {
        wx.authorize({
          scope: 'scope.userInfo',
          success() {
            wx.getUserInfo({
              lang:'zh_CN',
              success: function (res) {
                if(callback){ callback(res.userInfo); }
              }
            });
          }
        })
      }
    }
  })

}


/**
 * 计算指定日期与当前日期相差天数
 */
wx["$$timeDiff"] = function(time1){
  if(!time1){return 0;}
  var _t_f, _s_t_r, _now;
  var _t_f = new Date(time1);
  _now = new Date();//当前时间
  return parseInt((_t_f - _now) / 1000 / 60 / 60 / 24);
}

App({
  onLaunch: function () {
  
    var _this = this;
    wx.$$getOpenid(function (r) {
      _this.globalData.wxopenId = r;
    });
    
    wx.$$getWXUserInfo(function(r){
      _this.globalData.wxUserInfo = r;
    })
  },

  globalData: {
    userInfo: wx.getStorageSync("__userInfo") || undefined,
    wxUserInfo:{},
    wxopenId: undefined,
    GoUrl: true,
    DataStatistics:{
      ActivityCount: 0,
      AntifakeCount: 0,
      AntifleeingCount: 0,
      GenCodeCount: 0,
      HScanCount: 0,
      TScanCount: 0
    }
  },
  /**
  * POST 请求
  */
  _post: function (__param, __showloading = true) {
    __set_ajax(__param.url, __param.data, __param.success, __param.fail, "POST", __showloading);
  },
  /**
   * GET 请求
   */
  _get: function (__param, __showloading = true) {
    __set_ajax(__param.url, __param.data, __param.success, __param.fail, "GET", __showloading);
  },
  /**
  * PUT 请求
  */
  _put: function (__param, __showloading = true) {
    __set_ajax(__param.url, __param.data, __param.success, __param.fail, "PUT", __showloading);
  },
  /**
  * DELETE 请求
  */
  _delete: function (__param, __showloading = true) {
    __set_ajax(__param.url, __param.data, __param.success, __param.fail, "DELETE", __showloading);
  },

  openView: function (__url) {
    var _this = this;
    if (!_this.globalData.GoUrl) { return; }
    _this.globalData.GoUrl = false;
    setInterval(function () {
      _this.globalData.GoUrl = true;
    }, 2500);
    if (_this.globalData.userInfo) {
      wx.navigateTo({
        url: __url
      })
    } else {
      var _current = getCurrentPages();
      var _routes = _current[_current.length - 1].route;
      wx.navigateTo({
        url: '../my/logon/logon?_backurl=' + "../../" + _routes.substring((_current[_current.length - 1].route.indexOf("/", (_routes.indexOf('/') + 1))) + 1) + "/" + __url,
      })
    }
  },
  openView2: function (__url, __vaildUrl, __userId, __toast = "条码错误", __single = true) {
    wx.scanCode({
      success: function (r) {
        if (r.result) {
          if (__vaildUrl) {
            getApp()._get({
              url: __vaildUrl,
              data: { code: r.result, userId: __userId, proId: 0 },
              success: function (succ) {
                if (succ) {
                  var _condition = "";
                  if (succ instanceof Object) {
                    for (var i in succ) {
                      _condition += "&" + i + "=" + succ[i];
                    }
                  }
                  wx.navigateTo({
                    url: __url + '?code=' + r.result + _condition,
                  })
                } else {
                  if (succ.message) {
                    __toast = succ.message;
                  }
                  wx.showModal({
                    title: '提示',
                    content: __toast + ",是否继续?",
                    success: function (r2) {
                      if (!r2.cancel) {
                        getApp().openView2(__url, __vaildUrl, __userId, __toast, __single);
                      }
                    }
                  })
                }
              },
              fail: function (ex) {
                if (ex) {
                  __toast = ex;
                }
                wx.showModal({
                  title: '提示',
                  content: __toast + ",是否继续?",
                  success: function (r2) {
                    if (!r2.cancel) {
                      getApp().openView2(__url, __vaildUrl, __userId, __toast, __single);
                    }
                  }
                })
              }
            });
          }
        } else {
          wx.showModal({
            title: '提示',
            content: '未正确认别二维码',
            showCancel: false,
            success: function (r1) {
              if (!r1.cancel) {
                getApp().openView2(__url, __vaildUrl, __userId, __toast, __single);
              }
            }
          })
        }
      }
    })
  },
  pages: new __Pages(),

  uploadFile: function (param) {
    if (param) {
      wx.uploadFile({
        url: GlobalConfig.API_Url + param.url,
        filePath: param.filepath,
        name: param.file,
        success: function (e) {
          if (param.success) {
            param.success(JSON.parse(e.data));
          }
        },
        fail: function (r) {
          wx.showModal({
            title: '错误',
            content: '文件上传失败',
            showCancel: false
          })
        }
      })
    } else {
      throw Error("参数丢失");
    }
  },
  //非空校验
  vaild: function (option, title) {
    if (option == '' || option == null) {
      wx.showModal({
        title: title,
        content: '不能为空',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  }
  ,
  /**
   * 获取当前指定格式的时间
   */

  _formatTime: function (fmt) {
    var _this = new Date();
    var o = {
      "M+": _this.getMonth() + 1,                 //月份 
      "d+": _this.getDate(),                    //日 
      "h+": _this.getHours(),                   //小时 
      "m+": _this.getMinutes(),                 //分 
      "s+": _this.getSeconds(),                 //秒 
      "q+": Math.floor((_this.getMonth() + 3) / 3), //季度 
      "S": _this.getMilliseconds()             //毫秒 
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (_this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      }
    }
    return fmt;
  }

})

/**
 * 搜索当前字符串中是否包含目标
 */
String.prototype.searchOf = function(p){
  if (this === undefined || this === "" || p === undefined || p === "") {
    return false;
  }
  if (this == p){
    return true;
  }
  var _array = this.split(",");
  var _result = false;
  for(var i = 0;i<_array.length;i++){
   if(_array[i]==p){
     _result = true;
     break;
   }
  }
  return _result;
}

// String.prototype.searchOf = function(sstring){
//   debugger
//   if (this === undefined || this === "" || sstring === undefined || sstring === ""){
//    return false;
//  }
//   if (this === sstring){ return true; }
//   if(this.length <= sstring.length){ return false; }
//   var _result = false;
//   var _ok = 0;
//   for(var i =0;i<this.length;i++){
//     if(this[i] == sstring[i]){
//       _ok+=1;
//       if(_ok == sstring.length){
//         if(this[i+1]!=sstring[i]){
//           _result = true;
//           break;
//         }
//       }else{ _result = false;break;}
//     }else{_ok = 0;}
//   }
//   return _result;
// }

//扩展Array
Array.prototype.appendArray = function (items) {
  if (items.length != 0) {
    for (var index = 0; index < items.length; index++) {
      this.push(items[index]);
    }
  }
  return this;
}

/**
 * 刷新页面模型
 */
wx["$$apply"] = function (__e, __model) {
  var __this = getCurrentPages()[getCurrentPages().length - 1];
  var __colname = __e.currentTarget.dataset.colname;
  if (__colname) {
    __model[__colname] = __e.detail.value;
    __this.setData(__this.data);
  } else {
    throw Error("当前标签不存在[data-colname]属性");
  }
}

/**
 * 获取当前页面父级
 */
wx["$$getParent"] = function () {
  var _pages = getCurrentPages();
  if (_pages.length == 1) { return _pages; }
  return _pages[_pages.length - 2];
}




